/*
   Copyright 2006 Gavin Bong

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.raverun;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.CommandListener;

import java.lang.Thread;

public class UIController implements Runnable, CommandListener
{
    public MainMidlet mMidlet;    
    ListContainer mMainMenuUI;    
    public static final Command mExitCommand = new Command("Exit", Command.EXIT, 10);
    private Display mDisplay;
    
    Thread m_animator;
    private Shared m_shared = new Shared();    

    public static final int DELAY = 200;
    
    public UIController( MainMidlet midlet )
    {
        ListContainer._("Construction of new UIController");
        mMidlet = midlet;
        mDisplay = Display.getDisplay( midlet );        
    }
    
    public void init() 
    {
        initMainMenuUI();        
        mDisplay.setCurrent( mMainMenuUI );
        startAnimatorThread();
    }    
    
    public void initMainMenuUI()
    {
        if (mMainMenuUI == null)
        {
            ListContainer._("Constructing the MAIN MENU");
            mMainMenuUI = new ListContainer( this, "main", m_shared);

            mMainMenuUI.append(new ListElement(mMainMenuUI, "One"));
            mMainMenuUI.append(new ListElement(mMainMenuUI, "Two"));
            mMainMenuUI.append(new ListElement(mMainMenuUI, "About"));
            mMainMenuUI.append(new ListElement(mMainMenuUI, "Pirates of the Carribean: Dead Man's chest"));        
            mMainMenuUI.append(new ListElement(mMainMenuUI, "An American Haunting"));        
            mMainMenuUI.append(new ListElement(mMainMenuUI, "Garfield: A tail of two kittens"));        
            mMainMenuUI.append(new ListElement(mMainMenuUI, "pneumonoultramicroscopicsilicovolcanoconiosis"));
            mMainMenuUI.append(new ListElement(mMainMenuUI, "0123456789012345678901234567890123456789"));

            mMainMenuUI.addCommand( mExitCommand );

            mMainMenuUI.init();                   
        }
    }
    
    public void commandAction(Command command, Displayable displayable)
    {
        if( command == mExitCommand )
        {
            exitRequested();
        }         
    }

    public void handleEvent(int eventId, Object selectedItem)
    {
        
    }
    
    private synchronized void startAnimatorThread()
    {
        if (m_animator == null) 
        {
            m_animator = new Thread( this );
            m_animator.start();        
        }
        else
        {
            if (!m_animator.isAlive())
                m_animator.start();
        }
    }
    
    public synchronized void stopAnimatorThread()
    {
        m_animator = null;        
        m_shared.setElement( ListElement.END_TOKEN, 0, 0, 0, 0 );           
        // should call m_animator.interrupt() but not supported in CLDC 1.0
    }
    
    public void run() 
    {        
        ListContainer._("Animation Thread started");          
        Thread currentThread = Thread.currentThread();

        long tickStartTime = 0L;
        long tickEndTime = 0L;
        int tickDuration = 0;
        
        while (currentThread == m_animator)
        {
	    tickStartTime = System.currentTimeMillis();            
            m_shared.tick();
            ListContainer._("tick");
            tickEndTime = System.currentTimeMillis();
            
            tickDuration = (int)(tickEndTime - tickStartTime); 
            if( tickDuration < DELAY )            
            {
                try
                {
                    Thread.sleep(DELAY - tickDuration);
                }
                catch( InterruptedException ignore )
                {
                }                
            }
        }        
        ListContainer._("Animation Thread dying");        
    }    
    
    public void exitRequested()
    {
        mMidlet.exit();
    }
    
    public final void updateList(Runnable runnable)
    {
        mDisplay.callSerially( runnable );
    }
    
}
